//
//  XNUserAccountViewModel.swift
//  weibo
//
//  Created by 王向宁 on 16/5/22.
//  Copyright © 2016年 王向宁. All rights reserved.
//

import UIKit

private let userInfoKey = "com.itheima.userInfoKey"

class XNUserAccountViewModel: NSObject {
    
    static let sharedAccountViewModel:XNUserAccountViewModel = XNUserAccountViewModel()
    
    var userAccount: XNUserAccount?
    
    //重写构造方法 在构造方法中 加载用户的账户模型
    // private 私有化构造方法
    private override init() {
        
        super.init()
        userAccount = loadUserAccount()
    }
    
    var userLogin: Bool {
        if userAccount?.expires_date?.compare(NSDate()) == .OrderedDescending {
            return true
        }
        
        //如果过期  需要将 userAccount 设置为 nil
        userAccount = nil
        return false
    }
    
    //增加一个用户头像地址
    //只读属性,特点:每次执行的时候都会进行运算
    var headURL : NSURL? {
        get {
            return NSURL(string : userAccount?.avatar_large ?? "")
        }
    }
    
    

}

extension XNUserAccountViewModel {
    func loadAccessToken(code: String, finished:(isSuccess: Bool) -> ()) {
        HMNetworkTools.sharedTools.loadAccessToken(code) { (responseObject, error) in
            if error != nil {
                finished(isSuccess: false)
                return
            }
            
            self.loadUserInfo(responseObject,finished: finished)
        }
        

    }
        
//        let urlString = "https://api.weibo.com/oauth2/access_token"
//        
//        let parameter = ["client_id" : client_id, "client_secret":client_secret, "grant_type": "authorization_code","code":code,"redirect_uri":redirect_uri]
//        
//        HMNetworkTools.sharedTools.request(.POST, urlString: urlString, parameters: parameter) { (responseObject, error) in
//            print(responseObject,error)
//            
//            //请求token成功之后,使用token和hid获取用户信息
//            
//            if error != nil {
//                finished(isSuccess: false)
//                return
//            }
//            
//            self.loadUserInfo(responseObject,finished: finished)
//        }
//        
//    }
    
    //请求用户信息
    private func loadUserInfo(response: AnyObject?,finished:(isSuccess: Bool) -> ()) {
        
        guard let result = response as? [String : AnyObject] else {
            finished(isSuccess: false)
            return
        }
        
        HMNetworkTools.sharedTools.loadUserInfo(result) { (responseObject, error) in
            if error != nil {
                finished(isSuccess: false)
                return
            }
            
            //请求成功
            guard var dict = responseObject as? [String : AnyObject] else {
                finished(isSuccess: false)
                return
            }
            
            //用户信息  就应该保存用户信息到本地
            //合并两个字典 统一保存用户数据到本地
            for (key, value) in result {
                dict[key] = value
            }
            
            //这段代码被移动到 分类中进行封装处理
            self.saveUserAccount(dict)
            //完成成功的回调
            finished(isSuccess: true)
        }
        
//        let token = result["access_token"]!
//        
//        let uid = result["uid"]!
//        
//        let urlString = "https://api.weibo.com/2/users/show.json"
//        
//        let parameters = ["access_token" : token,"uid" : uid]
//        
//        HMNetworkTools.sharedTools.request(.GET, urlString: urlString, parameters: parameters) { (responseObject, error) in
//            if error != nil {
//                
//                finished(isSuccess: false)
//                return
//            }
//            
//            //请求成功
//            guard var dict = responseObject as? [String : AnyObject] else {
//                finished(isSuccess: false)
//                return
//            }
//            
//            for (key, value) in result {
//                dict[key] = value
//            }
//            
//            self.saveUserAccount(dict)
//            
//            finished(isSuccess: true)
//        }

    }
}


//存储数据
extension XNUserAccountViewModel {
    //存储数据
    func saveUserAccount(dict: [String : AnyObject]) {
        
        //1.将dict转换为模型对象
        let user = XNUserAccount(dict: dict)
        
        // 为了 解决 从 未登录状态 -> 登陆状态 userAccount 为nil 的bug
        
        self.userAccount = user
        
        //2.将模型对象转字典
        let keys = ["access_token","expires_in","uid","name","avatar_large","expires_date"]
        
        let userInfo = user.dictionaryWithValuesForKeys(keys)
        
        //保存字典
        let userDefaults = NSUserDefaults.standardUserDefaults()
        
        userDefaults.setObject(userInfo, forKey: userInfoKey)
        
        //同步
        userDefaults.synchronize()
        
    }
    
    //取数据
    func loadUserAccount() -> XNUserAccount? {
        guard let dict = NSUserDefaults.standardUserDefaults().objectForKey(userInfoKey) as? [String : AnyObject] else {
            return nil
        }
        
        let user = XNUserAccount(dict: dict)
        
        return user
        
    }
}




